package com.mfnote.db.dao;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.mfnote.db.DBHelper;
import com.mfnote.db.DBInfo;
import com.mfnote.model.MainCountEntity;

/**
 * 主界面数据库操作类
 * @author ZHF
 *
 */
public class MainDao {

	public SQLiteDatabase db; // 系统提供的数据库
	private DBHelper dbHelper = null;
	

	public MainDao(Context context) {
		super();
		this.dbHelper =  DBHelper.getInstance(context);//用static方法来实例化该对象
	}

	/** 打开数据库 **/
	private void openDatabase() {
			db = dbHelper.getWritableDatabase(); // 这里根据数据库名和版本号判断，第一次就调用onCreate创建表，第二次若两者相同就直接返回，若不同调用onUpgrade
	}
	
	/** 查询所有表的记录 **/
	public ArrayList<MainCountEntity> getMainCount() {
		// 打开数据库
		openDatabase(); // 首次会新建表
		ArrayList<MainCountEntity> mainData = null; // 接收数据

		// Cursor----ResultSet:用于接收数据库数据列表
		Cursor cursor = db.query(DBInfo.Table.TB_MAINRECORD_NAME, null, null,null, null, null, null);
		
		if (null != cursor && cursor.getCount() > 0) {
			mainData = new ArrayList<MainCountEntity>();
			MainCountEntity mainCount = null;
			
			while (cursor.moveToNext()) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				int writeCount = cursor.getInt(cursor.getColumnIndex("writeCount"));
				int paintCount = cursor.getInt(cursor.getColumnIndex("paintCount"));
				int handCount = cursor.getInt(cursor.getColumnIndex("handCount"));
				int recordCount = cursor.getInt(cursor.getColumnIndex("recordCount"));

				mainCount = new MainCountEntity(writeCount, paintCount,handCount, recordCount);

				mainData.add(mainCount);
			}
		}
		cursor.close();
		db.close(); // 用完记得要关闭哦
		return mainData;
	}

	/**不仅要显示出来还要插入进去，为下次显示界面获取数据做准备**/
	public int updateMainCount(MainCountEntity maincountEntity) {
		//打开数据库
		openDatabase();
		//获取四张表的总记录，并更新数据库中对应的列

		ContentValues values = new ContentValues();

		values.put("writeCount", maincountEntity.getWriteCount());
		values.put("paintCount", maincountEntity.getPaintCount());
		values.put("handCount", maincountEntity.getHandCount());
		values.put("recordCount", maincountEntity.getRecordCount());

		int isflag = db.update(DBInfo.Table.TB_MAINRECORD_NAME, values, null,null);
		
		db.close(); // 用完记得要关闭哦
		return isflag;
	}
}
